/*
 * Copyright (C) 2016. For Intelligent Group.
 */

package com.intelligent.ispc.client.core.view.analysis.spc;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.intelligent.ispc.chart.spc.ControlChart;
import com.intelligent.ispc.chart.spc.NormalDistributionChart;
import com.intelligent.ispc.chart.spc.ScatterChart;
import com.intelligent.ispc.client.chart.ControlChartDynamicLineChart;
import com.intelligent.ispc.client.core.controller.SpcController;
import com.intelligent.ispc.client.core.controller.SystemController;
import com.intelligent.ispc.client.core.modal.spc.ChartDataModal;
import com.intelligent.ispc.client.core.modal.spc.TestItemTableModel;
import com.intelligent.ispc.client.core.validator.GroupsDto;
import com.intelligent.ispc.client.core.validator.SysSpcCcwDto;
import com.intelligent.ispc.client.core.validator.SysSpcDto;
import com.intelligent.ispc.client.core.validator.UslAndLslDto;
import com.intelligent.ispc.client.core.view.AbstractPanel;
import com.intelligent.ispc.client.core.view.MainPanel;
import com.intelligent.ispc.client.core.view.analysis.AnalysisFilePanel;
import com.intelligent.ispc.client.core.view.analysis.AnalysisItemPanel;
import com.intelligent.ispc.client.core.view.analysis.AnalysisSearchPanel;
import com.intelligent.ispc.client.event.ExportBtnEnabledEvent;
import com.intelligent.ispc.client.ex.CheckBoxHeadRenderer;
import com.intelligent.ispc.client.ex.JTextFieldEx;
import com.intelligent.ispc.client.ex.RoundRectLabel;
import com.intelligent.ispc.client.utils.*;
import com.intelligent.ispc.client.utils.validation.GuiComponentFactory;
import com.intelligent.ispc.common.utils.ApplicationException;
import com.intelligent.ispc.common.utils.ResourceBundleUtils;
import com.intelligent.ispc.common.utils.StringUtils;
import com.intelligent.ispc.constant.AppConstant;
import com.intelligent.ispc.core.dto.*;
import com.intelligent.ispc.r.dto.*;
import com.jgoodies.common.base.Strings;
import org.apache.commons.collections.map.HashedMap;
import org.jdesktop.beansbinding.BindingGroup;
import org.jdesktop.jxlayer.JXLayer;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.TableRowSorter;
import javax.swing.text.JTextComponent;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * Created by Peter on 2016/7/7.
 * Changed by tony.yu.
 */
@org.springframework.stereotype.Component
public class SpcMainPanel extends AbstractPanel {

    private TestItemTableModel testItemTableModel;
    private ChartDataModal chartDataModal;
    private GroupsDto groupsDto;
    private GroupsDto groupsDtoCache;
    private UslAndLslDto uslAndLslDto;
    private UslAndLslDto uslAndLslDtoCache;
    @Autowired
    private SpcController spcController;
    @Autowired
    private SystemController systemController;

    /**
     * Constructor
     */
    public SpcMainPanel() {
    }

    @Override
    public void initDataSource() {
        analysisFilePanel.initDataSource();
        analysisSearchPanel.setBaseFields(Lists.newArrayList());
        initAllModal();
        groupsDto = new GroupsDto();
        groupsDtoCache = new GroupsDto();
        uslAndLslDto = new UslAndLslDto();
        uslAndLslDtoCache = new UslAndLslDto();
        itemNameAndValueCache = new HashedMap();
        spcConfigDto = spcController.findSpcConfig();
        sysSpcDto = systemController.findSpcConfig();
    }

    @Override
    public void initView() {
        analysisFilePanel.initView();
        cleanAll();
    }

    @Override
    @PostConstruct
    public void initComponents() {
        rightPanel = new JPanel();
        chartTabPanel = new JTabbedPane();
        testDataPanel = new JPanel();
        testDataFilter = new JTextFieldEx();
        testDataAllButton = new JRadioButton("All");
        testDataSelectedButton = new JRadioButton("Selected");
        testDataUnSelectedButton = new JRadioButton("Unselected");

        testDataResetButton = new JButton("Reset");
        testDataTable = new JTable();
        testDataBg = new ButtonGroup();
        searchButton = new JButton("Search");
        analysisFilePanel = new AnalysisFilePanel(UIConstant.MODULE_SPC);
        analysisItemPanel = new AnalysisItemPanel(UIConstant.MODULE_SPC);
        analysisSearchPanel = new AnalysisSearchPanel(UIConstant.MODULE_SPC);
        bg = new BindingGroup();
        spcExportAllDialog = new SpcExportAllDialog();
        spcExportMultipleItemDialog = new SpcExportMultipleItemDialog();

        final Dimension analsissSearchPanelSize = new Dimension(150, 250);
        final Dimension cahrtTabPanelSize = new Dimension(600, 476);
        analysisSearchPanel.setPreferredSize(analsissSearchPanelSize);
        chartTabPanel.setPreferredSize(cahrtTabPanelSize);

        //init left search
        JPanel leftPanel = new JPanel(new GridBagLayout());
        leftPanel.add(analysisFilePanel, new GBC(0, 0).setFill(GBC.BOTH).setAnchor(GBC.NORTH).setWeight(100, 100));
        leftPanel.add(analysisItemPanel, new GBC(0, 1).setFill(GBC.BOTH).setAnchor(GBC.NORTH).setWeight(100, 100));
        leftPanel.add(analysisSearchPanel, new GBC(0, 2).setFill(GBC.BOTH).setAnchor(GBC.NORTH).setWeight(100, 100));
        leftPanel.add(searchButton, new GBC(0, 3).setFill(GBC.HORIZONTAL).setAnchor(GBC.NORTH).setWeight(100, 100));
        JScrollPane leftScroll = new JScrollPane();
        leftScroll.setViewportView(leftPanel);
        leftScroll.setBorder(BorderFactory.createEmptyBorder());
        leftScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        final Dimension leftScrollSize = new Dimension(200, 100);
        leftScroll.setPreferredSize(leftScrollSize);

//        popupMenu = new JPopupMenu();
//        popupMenu.add(spcExportAllCharts);
//        popupMenu.addSeparator();
//        popupMenu.add(spcExportMulNdCharts);

        spcChartRefreshButton = new JButton("Refresh Chart");

        JPanel topBarPanel = new JPanel(new GridBagLayout());
        JLabel titleLabel = new JLabel("Analysis/SPC");
        titleLabel.setFont(FontFactory.createPageTileFont());

        ndChartsEventTip = new JLabel();
        controlChartsEventTip = new JLabel();
        topBarPanel.add(titleLabel, new GBC(0, 0).setFill(GBC.HORIZONTAL).setInsets(0, 5, 0, 0));
        topBarPanel.add(ndChartsEventTip, new GBC(1, 0).setFill(GBC.HORIZONTAL).setWeight(100, 0).setInsets(0, 20, 0, 0));
        topBarPanel.add(controlChartsEventTip, new GBC(2, 0).setFill(GBC.HORIZONTAL).setWeight(100, 0).setInsets(0, 20, 0, 0));
        topBarPanel.add(new JLabel(), new GBC(3, 0).setFill(GBC.BOTH).setWeight(100, 0));
        topBarPanel.add(spcChartRefreshButton, new GBC(4, 0).setFill(GBC.HORIZONTAL));

        //init Chart Panel
        tabSubPanel = new JPanel[]{new JPanel(), new JPanel(), new JPanel(), new JPanel(), new JPanel(), new JPanel(), new JPanel()};
        chartTabPanel.addTab("ND Chart", tabSubPanel[0]);
        chartTabPanel.addTab("S Chart", tabSubPanel[1]);
        chartTabPanel.addTab("Run Chart", tabSubPanel[2]);
        chartTabPanel.addTab("XBar Chart", tabSubPanel[3]);
        chartTabPanel.addTab("SD Chart", tabSubPanel[4]);
        chartTabPanel.addTab("R Chart", tabSubPanel[5]);
        chartTabPanel.addTab("MR Chart", tabSubPanel[6]);

        //init Test Data Panel
        testDataPanel.setLayout(new GridBagLayout());
        testDataPanel.setBorder(BorderFactory.createTitledBorder("Test Data"));

        testDataFilter.setPlaceHolder("SerialNumber/Value");
        JPanel filterPanel = new JPanel(new GridBagLayout());
        testDataBg.add(testDataAllButton);
        testDataBg.add(testDataSelectedButton);
        testDataBg.add(testDataUnSelectedButton);
        testDataAllButton.setSelected(true);
        filterPanel.add(testDataFilter, new GBC(0, 0).setFill(GBC.HORIZONTAL).setWeight(50, 0));
        filterPanel.add(testDataAllButton, new GBC(1, 0).setFill(GBC.HORIZONTAL).setInsets(0, 10, 0, 0));
        filterPanel.add(testDataSelectedButton, new GBC(2, 0).setFill(GBC.HORIZONTAL).setInsets(0, 5, 0, 0));
        filterPanel.add(testDataUnSelectedButton, new GBC(3, 0).setFill(GBC.HORIZONTAL).setInsets(0, 5, 0, 0));
        filterPanel.add(new JPanel(), new GBC(4, 0).setFill(GBC.BOTH).setWeight(100, 100));
        filterPanel.add(testDataResetButton, new GBC(5, 0).setFill(GBC.HORIZONTAL));

        testDataTable.getTableHeader().setReorderingAllowed(false);
        JScrollPane testDataTableScroll = new JScrollPane();
        testDataTableScroll.setViewportView(testDataTable);
        testDataTableScroll.setBorder(BorderFactory.createEmptyBorder());

        testDataPanel.add(filterPanel, new GBC(0, 0).setFill(GBC.HORIZONTAL).setInsets(0, 0, 5, 0));
        testDataPanel.add(testDataTableScroll, new GBC(0, 1).setFill(GBC.BOTH).setWeight(100, 100));

        JScrollPane rightScrollPanel = new JScrollPane();
        rightScrollPanel.setViewportView(rightPanel);
        rightScrollPanel.setBorder(BorderFactory.createEmptyBorder());
        rightPanel.setBorder(BorderFactory.createEmptyBorder());
        rightPanel.setLayout(new GridBagLayout());
        rightPanel.add(topBarPanel, new GBC(0, 0).setFill(GBC.BOTH));
        rightPanel.add(chartTabPanel, new GBC(0, 1).setFill(GBC.BOTH));
        rightPanel.add(testDataPanel, new GBC(0, 2).setFill(GBC.BOTH));
        rightPanel.add(new JPanel(), new GBC(0, 3).setFill(GBC.BOTH).setWeight(100, 100));

        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, false, leftScroll, rightScrollPanel);
        splitPane.setDividerSize(5);

        this.setLayout(new GridBagLayout());
        this.add(splitPane, new GBC(0, 0).setFill(GBC.BOTH).setWeight(100, 100));

        controlChartDynamicLineChartMap = new HashedMap();
        initComponentListener();
    }

    public AnalysisItemPanel getAnalysisItemPanel() {
        return analysisItemPanel;
    }

    public AnalysisSearchPanel getAnalysisSearchPanel() {
        return analysisSearchPanel;
    }

    /**
     * Call when change the CSV file and analysis
     *
     * @param files file names
     */
    public void onFileChange(List<String> files) {
        cleanAll();
        analysisItemPanel.onFileChange(files);
        fileFlag = false;
        analyseFlag = false;
        searchKeyFlag = false;
        searchFlag = false;
        testItemFlag = false;
        setBtnEnable();
    }

    /**
     * Check changed the selected the CSV files whether or not
     *
     * @param isMatched isMatched
     */
    public void onChooseFileChange(boolean isMatched) {
        fileFlag = isMatched;
        setBtnEnable();
    }

    /**
     * Check changed the selected the testItem whether or not
     *
     * @param isMatched isMatched
     */
    public void onChooseItemChange(boolean isMatched) {
        testItemFlag = isMatched;
        setBtnEnable();
    }

    /**
     * Check changed the query conditions whether or not
     *
     * @param isMatched isMatched
     */
    public void onSearchConditionChange(boolean isMatched) {
        searchKeyFlag = isMatched;
        setBtnEnable();
    }

    /**
     * Analysis the csv files successful
     */
    public void analysisSuccessful() {
        List<KeyValueDto> fileDataDtos = analysisFilePanel.getSelectedFiles();
        List<String> filePath = Lists.newArrayList();
        for (int i = 0; i < fileDataDtos.size(); i++) {
            filePath.add((String) fileDataDtos.get(i).getValue());
        }
        itemNameAndValueCache = new HashedMap();
        analyseFlag = true;
        fileFlag = true;
        setBtnEnable();
    }

    /**
     * Analysis the testItem successful
     *
     * @param spcResultDto spcResultDto
     */
    public void searchSuccessful(SpcResultDto spcResultDto) {
        analysisSearchPanel.setCacheData(analysisSearchPanel.getSearchParams());
        if (spcResultDto == null) {
            chartDataModal.add(ChartDataModal.CHART_NDC, null);
            chartDataModal.add(ChartDataModal.CHART_SC, null);
            chartDataModal.add(ChartDataModal.CHART_RUN, null);
            chartDataModal.add(ChartDataModal.CHART_XBAR, null);
            chartDataModal.add(ChartDataModal.CHART_SD, null);
            chartDataModal.add(ChartDataModal.CHART_R, null);
            chartDataModal.add(ChartDataModal.CHART_MR, null);

            drawAllChart();
            this.updateUI();
        } else {
            List<TestItemDto> dtos = spcResultDto.getTestItems();
            if (testItemTableModel.getData() == null || testItemTableModel.getData().isEmpty()) {
                testItemTableModel.setData(dtos);
                testItemTableModel.setViewData(getTableViewData());
            } else {
                String usl = uslAndLslDto.getUslValue();
                String lsl = uslAndLslDto.getLslValue();
                for (int i = 0; i < dtos.size(); i++) {
                    if (StringUtils.isBlank(usl)) {
                        testItemTableModel.getData().get(i).setUsl("");
                    } else if (StringUtils.isNumeric(usl)) {
                        testItemTableModel.getData().get(i).setUsl(usl);
                    }
                    if (StringUtils.isBlank(lsl)) {
                        testItemTableModel.getData().get(i).setLsl("");
                    } else if (StringUtils.isNumeric(lsl)) {
                        testItemTableModel.getData().get(i).setLsl(lsl);
                    }
                    testItemTableModel.getData().get(i).setPass(dtos.get(i).getPass());
                }
            }
            // NDC Chart Data Modal
            Map<String, Object> result = spcResultDto.getChartData();
            NormalDistributionDto normalDistributionDto = (NormalDistributionDto) result.get("NDC");
            ScatterDto scatterDto = (ScatterDto) result.get("SCATTER");
            ControlDataDto controlDataDto1 = (ControlDataDto) result.get("RUNC");
            ControlDataDto controlDataDto2 = (ControlDataDto) result.get("XBARC");
            ControlDataDto controlDataDto3 = (ControlDataDto) result.get("SDC");
            ControlDataDto controlDataDto4 = (ControlDataDto) result.get("RC");
            ControlDataDto controlDataDto5 = (ControlDataDto) result.get("MRC");

            chartDataModal.add(ChartDataModal.CHART_NDC, normalDistributionDto);
            chartDataModal.add(ChartDataModal.CHART_SC, scatterDto);
            chartDataModal.add(ChartDataModal.CHART_RUN, controlDataDto1);
            chartDataModal.add(ChartDataModal.CHART_XBAR, controlDataDto2);
            chartDataModal.add(ChartDataModal.CHART_SD, controlDataDto3);
            chartDataModal.add(ChartDataModal.CHART_R, controlDataDto4);
            chartDataModal.add(ChartDataModal.CHART_MR, controlDataDto5);

            ndChartsEventTip.setText("");
            controlChartsEventTip.setText("");
            drawAllChart();
            this.updateUI();

            searchKeyFlag = true;
            searchFlag = true;
            testItemFlag = true;
            setBtnEnable();
        }
    }

    /**
     * Check the searchButton is working or not
     *
     * @return true when the button is valid
     */
    public boolean getSearchBtnStatus() {
        return searchButton.isEnabled();
    }

    /**
     * Make the ExportButton to display or not
     *
     * @param invoker current component
     */
    public void showExportMenu(Component invoker) {
        showExportDialog();
    }

    /**
     * Response to the searchButton or double click testItem's event
     */
    public void fireSearchActionPerformed() {
        try {
            fireCleanPanel();
            List<KeyValueDto> fileDataDtos = analysisFilePanel.getSelectedFiles();
            if (fileDataDtos == null || fileDataDtos.isEmpty()) {
                throw new UIException(ExceptionMessages.EXCEPTION_SPC_NO_SELECT_FILE);
            }
            String testItemName = analysisItemPanel.getSelectedName();
            if (StringUtils.isBlank(testItemName)) {
                throw new UIException(ExceptionMessages.EXCEPTION_SPC_NO_SELECT_ITEM);
            }
            List<String> testItemNameList = new ArrayList<String>();
            testItemNameList.add(testItemName);
            List<DynSearchFieldDto> dynSesrchFieldDtos = analysisSearchPanel.getSearchParams();
            List<TestItemDto> excludeItems = null;

            String[] chartNamesArray = {AppConstant.CHART_TYPE_SPC_ND, AppConstant.CHART_TYPE_SPC_SCT, AppConstant.CHART_TYPE_SPC_XBAR,
                    AppConstant.CHART_TYPE_SPC_RUN, AppConstant.CHART_TYPE_SPC_MR, AppConstant.CHART_TYPE_SPC_R, AppConstant.CHART_TYPE_SPC_SD};
            List<String> chartNames = new ArrayList<>();
            Collections.addAll(chartNames, chartNamesArray);

            Map<String, List<DynSearchFieldDto>> dynSesrchFieldDtosMap = new HashedMap();
            Map<String, List<TestItemDto>> excludeItemsMap = new HashedMap();
            Map<String, List<String>> chartNamesMap = new HashedMap();
            dynSesrchFieldDtosMap.put(testItemName, dynSesrchFieldDtos);
            excludeItemsMap.put(testItemName, excludeItems);
            chartNamesMap.put(testItemName, chartNames);

            spcController.findData(fileDataDtos, dynSesrchFieldDtosMap, testItemNameList, excludeItemsMap, itemNameAndValueCache, chartNamesMap);

            ((CheckBoxHeadRenderer) testDataTable.getTableHeader().getDefaultRenderer()).setCheckboxSelect(true);

        } catch (UIException e) {
            AppMessageFactory.showWarningDialog(ResourceBundleUtils.getString(e.getMessage()));
        } catch (ApplicationException e) {
            AppMessageFactory.showWarningDialog(ResourceBundleUtils.getString(ExceptionMessages.EXCEPTION_GLOBAL_SYSTEM));
        }
    }

    private void initAllModal() {
        String[] colTestData = AppConstant.SPC_TEST_DATA_TABLE_TITLE;
        testItemTableModel = new TestItemTableModel(colTestData);
        testDataTable.setModel(testItemTableModel);
        testDataTable.getColumnModel().getColumn(0).setMinWidth(40);
        testDataTable.getColumnModel().getColumn(0).setMaxWidth(40);
        testDataTable.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);

        testDataTable.getTableHeader().setDefaultRenderer(new CheckBoxHeadRenderer(testDataTable));

        testDataTableSorter = new TableRowSorter(testItemTableModel);
        testDataTable.setRowSorter(testDataTableSorter);

        //Format the testDataTable: center and added the color
        TestDataTableRender render = new TestDataTableRender(testDataTable);
        testDataTable.setDefaultRenderer(Object.class, render);

        //set chart modal
        chartDataModal = new ChartDataModal();
        chartDataModal.add(ChartDataModal.CHART_NDC, Lists.newArrayList());
        chartDataModal.add(ChartDataModal.CHART_SC, Lists.newArrayList());
        chartDataModal.add(ChartDataModal.CHART_RUN, Lists.newArrayList());
        chartDataModal.add(ChartDataModal.CHART_XBAR, Lists.newArrayList());
        chartDataModal.add(ChartDataModal.CHART_SD, Lists.newArrayList());
        chartDataModal.add(ChartDataModal.CHART_R, Lists.newArrayList());
        chartDataModal.add(ChartDataModal.CHART_MR, Lists.newArrayList());
    }

    private void cleanAll() {
        fireCleanPanel();
        analysisItemPanel.onReceivedTestItems(new ArrayList<>());
        analysisSearchPanel.setBaseFields(new ArrayList<>());
        fileFlag = false;
        analyseFlag = false;
        searchKeyFlag = false;
        searchFlag = false;
        testItemFlag = false;
        setBtnEnable();
    }

    private void fireCleanPanel() {
        for (int i = 0; i < 7; i++) {
            tabSubPanel[i].removeAll();
            tabSubPanel[i].updateUI();
        }
        testDataFilter.setText(null);
        testItemTableModel.getData().clear();
        testDataTable.updateUI();
        testItemTableModel.fireTableDataChanged();
        ndChartsEventTip.setText("");
        controlChartsEventTip.setText("");
    }

    private void refreshCharts() {

        if (StringUtils.isNotBlank(uslAndLslDto.getLslValue())) {
            if (!StringUtils.isNumeric(uslAndLslDto.getLslValue())) {
                return;
            }
        }
        if (StringUtils.isNotBlank(uslAndLslDto.getUslValue())) {
            if (!StringUtils.isNumeric(uslAndLslDto.getUslValue())) {
                return;
            }
        }
        String testItemName = analysisItemPanel.getSelectedName();
        List<String> testItemNameList = new ArrayList<String>();
        testItemNameList.add(testItemName);

        List<DynSearchFieldDto> dynSesrchFieldDtos = analysisSearchPanel.getSearchParams();
        Map<String, List<DynSearchFieldDto>> dynSesrchFieldDtosMap = new HashedMap();
        dynSesrchFieldDtosMap.put(testItemName, dynSesrchFieldDtos);

        List<KeyValueDto> fileDataDtos = analysisFilePanel.getSelectedFiles();

        NDStandardDto ndStandardDto = new NDStandardDto();
        if (uslAndLslDto.getUslValue() == null || uslAndLslDto.getUslValue().isEmpty()) {
            ndStandardDto.setUslValue(null);
        } else if (StringUtils.isNumeric(uslAndLslDto.getUslValue())) {
            ndStandardDto.setUslValue(Double.valueOf(uslAndLslDto.getUslValue()));
        } else {
            return;
        }
        if (uslAndLslDto.getLslValue() == null || uslAndLslDto.getLslValue().isEmpty()) {
            ndStandardDto.setLslValue(null);
        } else if (StringUtils.isNumeric(uslAndLslDto.getLslValue())) {
            ndStandardDto.setLslValue(Double.valueOf(uslAndLslDto.getLslValue()));
        } else {
            return;
        }
        if (StringUtils.isNotBlank(uslAndLslDto.getUslValue()) && StringUtils.isNotBlank(uslAndLslDto.getLslValue())) {
            if (Double.valueOf(uslAndLslDto.getUslValue()) <= Double.valueOf(uslAndLslDto.getLslValue())) {
                AppMessageFactory.showWarningDialog("The LSL's value must less than the USL");
                return;
            }
        }
        String group = groupsDto.getGroups();
        if (group == null || group.isEmpty()) {
            return;
        } else if (!StringUtils.isNumeric(group)) {
            return;
        } else {
            try {
                int groupValue = Integer.parseInt(group);
                if (groupValue < 1 || groupValue > 2147483647) {
                    return;
                } else {
                    ndStandardDto.setGroupValue(groupValue);
                }
            } catch (NumberFormatException e) {
                return;
            }
        }

        String currentTestItemName = analysisItemPanel.getSelectedName();
        Map<String, List<TestItemDto>> excludeItemsMap = Maps.newHashMap();
        for (String name : testItemNameList) {
            List<TestItemDto> excludeItems;
            if (name.equals(currentTestItemName)) {
                excludeItems = new ArrayList<>();
                for (int i = 0; i < testItemTableModel.getRowCount(); i++) {
                    TestItemDto testItemDto = testItemTableModel.getData().get(i);
                    if (testItemDto.getCheck() != null && !testItemDto.getCheck()) {
                        excludeItems.add(testItemDto);
                    }
                }
                excludeItemsMap.put(currentTestItemName, excludeItems);
            } else {
                excludeItems = null;
            }
        }

        Map<String, NDStandardDto> ndStandardDtoMap = new HashedMap();
        ndStandardDtoMap.put(testItemName, ndStandardDto);

        String[] chartNamesArray = {AppConstant.CHART_TYPE_SPC_ND, AppConstant.CHART_TYPE_SPC_SCT, AppConstant.CHART_TYPE_SPC_XBAR,
                AppConstant.CHART_TYPE_SPC_RUN, AppConstant.CHART_TYPE_SPC_MR, AppConstant.CHART_TYPE_SPC_R, AppConstant.CHART_TYPE_SPC_SD};
        List<String> chartNames = new ArrayList<>();
        Collections.addAll(chartNames, chartNamesArray);
        Map<String, List<String>> chartNamesMap = new HashedMap();
        chartNamesMap.put(testItemName, chartNames);

        spcController.findData(fileDataDtos, dynSesrchFieldDtosMap, testItemNameList, excludeItemsMap, ndStandardDtoMap, chartNamesMap);
        groupsDtoCache.setGroups(groupsDto.getGroups());
        uslAndLslDtoCache.setUslValue(uslAndLslDto.getUslValue());
        uslAndLslDtoCache.setLslValue(uslAndLslDto.getLslValue());
        itemNameAndValueCache.put(analysisItemPanel.getSelectedName(), ndStandardDto);
    }

    private void initComponentListener() {

        testDataFilter.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                update(e);
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                update(e);
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                update(e);
            }

            private void update(DocumentEvent e) {
                testDataFilterListener();
            }
        });

        testDataAllButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                radioActionPerformed(AppConstant.SPC_ITEM_RADIO_ALL);
                testDataTable.updateUI();
            }
        });

        testDataSelectedButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                radioActionPerformed(AppConstant.SPC_ITEM_RADIO_SELECT);
                ((CheckBoxHeadRenderer) testDataTable.getTableHeader().getDefaultRenderer()).setCheckboxSelect(true);
                testDataTable.updateUI();
            }
        });

        testDataUnSelectedButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                radioActionPerformed(AppConstant.SPC_ITEM_RADIO_UNSELECT);
                ((CheckBoxHeadRenderer) testDataTable.getTableHeader().getDefaultRenderer()).setCheckboxSelect(false);
                testDataTable.updateUI();
            }
        });

        testDataResetButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                testDataAllButton.setSelected(true);
                radioActionPerformed(AppConstant.SPC_ITEM_RADIO_ALL);
                testDataTableSorter.setRowFilter(null);
                testDataFilter.setText("");
                ((CheckBoxHeadRenderer) testDataTable.getTableHeader().getDefaultRenderer()).setCheckboxSelect(true);
                testDataTable.updateUI();
            }
        });

        testDataTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                testCheckBoxClicked(e);
            }
        });

        searchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                fireSearchActionPerformed();
                analysisItemPanel.setCacheData(analysisItemPanel.getSelectedName());
            }
        });

        spcChartRefreshButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                refreshCharts();
            }
        });

        spcExportAllDialog.getSubmitBtn().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                if (spcExportAllDialog.getChartNames().size() == 0) {
                    AppMessageFactory.showWarningDialog("Please choose the charts name");
                    return;
                }
                List<KeyValueDto> files = analysisFilePanel.getSelectedFiles();
                List<String> testItemNameList = spcExportMultipleItemDialog.getSelectedItemName();
                List<DynSearchFieldDto> dynSearchFieldDtos = analysisSearchPanel.getSearchParams();
                List<String> chartNames = spcExportAllDialog.getChartNames();

                Map<String, ChartDto> guidesParams = new HashedMap();
                for (String name : chartNames) {
                    if (AppConstant.CHART_TYPE_SPC_RUN.equals(name)) {
                        ControlChartDynamicLineChart chart = controlChartDynamicLineChartMap.get("Run Chart");
                        if (chart != null) {
                            ChartDto chartDto = chart.exportBuildChart();
                            guidesParams.put(AppConstant.CHART_TYPE_SPC_RUN, chartDto);
                        } else {
                            guidesParams.put(AppConstant.CHART_TYPE_SPC_RUN, null);
                        }
                    } else if (AppConstant.CHART_TYPE_SPC_MR.equals(name)) {
                        ControlChartDynamicLineChart chart = controlChartDynamicLineChartMap.get("MR Chart");
                        if (chart != null) {
                            ChartDto chartDto = chart.exportBuildChart();
                            guidesParams.put(AppConstant.CHART_TYPE_SPC_MR, chartDto);
                        } else {
                            guidesParams.put(AppConstant.CHART_TYPE_SPC_MR, null);
                        }
                    }
                }

                String cacheTestItemName = analysisItemPanel.getCacheData();
                Map<String, List<TestItemDto>> excludeItemsMap = new HashedMap();
                for (String name : testItemNameList) {
                    List<TestItemDto> excludeItems;
                    if (name.equals(cacheTestItemName)) {
                        excludeItems = new ArrayList<>();
                        for (int i = 0; i < testItemTableModel.getRowCount(); i++) {
                            TestItemDto testItemDto = testItemTableModel.getData().get(i);
                            if (testItemDto.getCheck() != null && !testItemDto.getCheck()) {
                                excludeItems.add(testItemDto);
                            }
                        }
                        excludeItemsMap.put(name, excludeItems);
                        if (searchFlag) {
                            if (excludeItemsMap.get(name).size() == dataCount) {
                                AppMessageFactory.showWarningDialog("Please choose the test data");
                                return;
                            }
                        }
                    } else {
                        excludeItemsMap.put(name, null);
                    }
                }


                spcController.exportChart(files, testItemNameList, dynSearchFieldDtos, chartNames, guidesParams, excludeItemsMap, itemNameAndValueCache);
                spcExportAllDialog.setVisible(false);
            }
        });

        spcExportMultipleItemDialog.getNextStepBtnBtn().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                if (spcExportMultipleItemDialog.getSelectedCount() <= 0) {
                    AppMessageFactory.showWarningDialog("Please choose the testItem");
                } else {
                    spcExportMultipleItemDialog.setVisible(false);
                    final Dimension exportDialogSize = new Dimension(350, 400);
                    spcExportAllDialog.setPreferredSize(exportDialogSize);
                    spcExportAllDialog.pack();
                    spcExportAllDialog.setModal(true);
                    spcExportAllDialog.setLocationRelativeTo(ApplicationBeanUtils.getBean(MainPanel.class));
                    spcExportAllDialog.setCheckBoxSelected();
                    spcExportAllDialog.setVisible(true);
                }
            }
        });
    }

    private void showExportDialog() {
        final Dimension exportDialogSize = new Dimension(350, 400);
        spcExportMultipleItemDialog.setData(analysisItemPanel.getItemNames());
        spcExportMultipleItemDialog.setPreferredSize(exportDialogSize);
        spcExportMultipleItemDialog.pack();
        spcExportMultipleItemDialog.setModal(true);
        spcExportMultipleItemDialog.setLocationRelativeTo(ApplicationBeanUtils.getBean(MainPanel.class));
        spcExportMultipleItemDialog.setVisible(true);
        spcExportMultipleItemDialog.setCheckboxUnSelect(false);
        spcExportMultipleItemDialog.cleanFilter();
    }

    private void radioActionPerformed(String type) {
        final int filterColumn = 5;
        List<RowFilter<Object, Object>> scopeList = new ArrayList<RowFilter<Object, Object>>();
        RowFilter textFilter = RowFilter.regexFilter(testDataFilter.getText(), 1, filterColumn);
        if (AppConstant.SPC_ITEM_RADIO_SELECT.equals(type)) {
            scopeList.add(RowFilter.regexFilter("true", 0));
        } else if (AppConstant.SPC_ITEM_RADIO_UNSELECT.equals(type)) {
            scopeList.add(RowFilter.regexFilter("false", 0));
        } else {
            scopeList.add(RowFilter.regexFilter("", 0));
        }
        if (testDataFilter.getText().length() != 0) {
            scopeList.add(textFilter);
        }
        testDataTableSorter.setRowFilter(RowFilter.andFilter(scopeList));
        testDataTable.repaint();
        testItemTableModel.setViewData(getTableViewData());
    }

    private void testDataFilterListener() {
        final int filterColumn = 5;
        String type = null;
        if (testDataSelectedButton.isSelected()) {
            type = AppConstant.SPC_ITEM_RADIO_SELECT;
        } else if (testDataUnSelectedButton.isSelected()) {
            type = AppConstant.SPC_ITEM_RADIO_UNSELECT;
        }
        List<RowFilter<Object, Object>> scopeList = new ArrayList<RowFilter<Object, Object>>();
        RowFilter textFilter = RowFilter.regexFilter(testDataFilter.getText(), 1, filterColumn);
        if (AppConstant.SPC_ITEM_RADIO_SELECT.equals(type)) {
            scopeList.add(RowFilter.regexFilter("true", 0));
        } else if (AppConstant.SPC_ITEM_RADIO_UNSELECT.equals(type)) {
            scopeList.add(RowFilter.regexFilter("false", 0));
        } else {
            scopeList.add(RowFilter.regexFilter("", 0));
        }
        String value = testDataFilter.getText();
        if (value.length() != 0) {
            scopeList.add(textFilter);
        }
        testDataTableSorter.setRowFilter(RowFilter.andFilter(scopeList));
        testDataTable.repaint();
        testItemTableModel.setViewData(getTableViewData());
    }

    private void testCheckBoxClicked(MouseEvent ex) {
        if (ex.getClickCount() == 1) {
            int columnIndex = testDataTable.columnAtPoint(ex.getPoint());
            int row = testDataTable.rowAtPoint(ex.getPoint());
            int rowIndex = testDataTable.convertRowIndexToModel(row);
            if (columnIndex == 0) {
                if (testItemTableModel.getValueAt(rowIndex, 0) == null) {
                    return;
                }
                if (((Boolean) testItemTableModel.getValueAt(rowIndex, 0))) {
                    testItemTableModel.setValueAt(false, rowIndex, 0);
                } else {
                    testItemTableModel.setValueAt(true, rowIndex, 0);
                }
                testDataTable.repaint();
            }
        }
    }

    private void drawAllChart() {
        drawNdcPanel();
        drawScatterChart();
        for (int i = 2; i < tabSubPanel.length; i++) {
            drawControlChartPanel(i);
        }
    }

    private void drawNdcPanel() {
        if (tabSubPanel[0] != null) {
            tabSubPanel[0].removeAll();
        } else {
            tabSubPanel[0] = new JPanel();
        }
        if (chartDataModal.getData(ChartDataModal.CHART_NDC) == null) {
            return;
        }
        NormalDistributionDto ndcDM = (NormalDistributionDto) chartDataModal.getData(ChartDataModal.CHART_NDC);

        tabSubPanel[0].setLayout(new GridBagLayout());
        JPanel ndcLeftPanel = new JPanel();
        ndcLeftPanel.setLayout(new GridBagLayout());

        String[] labelNames = new String[]{
                "Statistical", "Samples", "AVG", "Max", "Min", "Range", "StDev", "LCL", "UCL", "Kurtosis", "Skewness",
                "AppConstant", "Groups", "USL", "LSL", "Center",
                "Capability Index", "CA(%)", "CPK", "CP", "CPL", "CPU"};
        int i;
        for (i = 0; i < labelNames.length; i++) {
            JLabel label = new JLabel();
            label.setText(labelNames[i]);
            ndcLeftPanel.add(label, new GBC(0, i).setFill(GBC.HORIZONTAL));
            if (i == 0 || i == 11 || i == 16) {
                label.setFont(label.getFont().deriveFont(Font.BOLD));
                ndcLeftPanel.add(label, new GBC(0, i, 2, 1).setFill(GBC.HORIZONTAL));
            }
        }

        boolean statistics = true;
        if (ndcDM.getStatisticsDto() == null) {
            statistics = false;
        }
        JLabel jlabel1 = new JLabel();
        dataCount = ndcDM.getStatisticsDto().getDataCount();
        jlabel1.setText(statistics ? StringUtils.formatBigDecimal((int) ((double) dataCount) + "") : "-");
        jlabel1.setHorizontalAlignment(SwingConstants.RIGHT);
        JLabel jlabel2 = new JLabel();
        Double avgValue = ndcDM.getStatisticsDto().getAvgValue();
        jlabel2.setText(statistics ? StringUtils.formatBigDecimal(valueIntoString(avgValue, jlabel2)) : "-");
        JLabel jlabel3 = new JLabel();
        Double maxValue = ndcDM.getStatisticsDto().getMaxValue();
        jlabel3.setText(statistics ? StringUtils.formatBigDecimal(valueIntoString(maxValue, jlabel3)) : "-");
        JLabel jlabel4 = new JLabel();
        Double minValue = ndcDM.getStatisticsDto().getMinValue();
        jlabel4.setText(statistics ? StringUtils.formatBigDecimal(valueIntoString(minValue, jlabel4)) : "-");
        JLabel jlabel5 = new JLabel();
        Double rangeValue = ndcDM.getStatisticsDto().getRangeValue();
        jlabel5.setText(statistics ? StringUtils.formatBigDecimal(valueIntoString(rangeValue, jlabel5)) : "-");
        JLabel jlabel6 = new JLabel();
        Double stdValue = ndcDM.getStatisticsDto().getStdValue();
        jlabel6.setText(statistics ? StringUtils.formatBigDecimal(valueIntoString(stdValue, jlabel6)) : "-");
        JLabel jlabel7 = new JLabel();
        Double lclValue = ndcDM.getStatisticsDto().getLclValue();
        jlabel7.setText(statistics ? StringUtils.formatBigDecimal(valueIntoString(lclValue, jlabel7)) : "-");
        JLabel jlabel8 = new JLabel();
        Double uclValue = ndcDM.getStatisticsDto().getUclValue();
        jlabel8.setText(statistics ? StringUtils.formatBigDecimal(valueIntoString(uclValue, jlabel8)) : "-");
        JLabel jlabel9 = new JLabel();
        Double kurtosisValue = ndcDM.getStatisticsDto().getKurtosisValue();
        jlabel9.setText(statistics ? StringUtils.formatBigDecimal(valueIntoString(kurtosisValue, jlabel9)) : "-");
        JLabel jlabel10 = new JLabel();
        Double skewnessValue = ndcDM.getStatisticsDto().getSkewnessValue();
        jlabel10.setText(statistics ? StringUtils.formatBigDecimal(valueIntoString(skewnessValue, jlabel10)) : "-");
        boolean statistics1 = true;
        if (ndcDM.getStandardDto() == null) {
            statistics1 = false;
        }

        jlabel12 = GuiComponentFactory.createTextField(bg, groupsDto, groupsDto.PROPERTYNAME_GROUPS);
        int groups = ndcDM.getStandardDto().getGroupValue();
        jlabel12.getView().setText(statistics1 ? StringUtils.formatBigDecimal(groups + "") : "-");
        groupsDtoCache.setGroups(String.valueOf(groups));
        ((JTextField) (jlabel12.getView())).setHorizontalAlignment(SwingConstants.RIGHT);

        jlabel13 = GuiComponentFactory.createTextField(bg, uslAndLslDto, uslAndLslDto.PROPERTYNAME_USL);
        Double tempUsl = ndcDM.getStandardDto().getUslValue();
        String uslValue = null;
        if (tempUsl != null) {
            uslValue = tempUsl + "";
        } else {
            uslValue = "";
        }
        jlabel13.getView().setText(StringUtils.formatBigDecimal(uslValue));
        uslAndLslDtoCache.setUslValue(uslValue);
        ((JTextField) (jlabel13.getView())).setHorizontalAlignment(SwingConstants.RIGHT);
        jlabel14 = GuiComponentFactory.createTextField(bg, uslAndLslDto, uslAndLslDto.PROPERTYNAME_LSL);
        Double tempLsl = ndcDM.getStandardDto().getLslValue();
        String lslValue = null;
        if (tempLsl != null) {
            lslValue = tempLsl + "";
        } else {
            lslValue = "";
        }
        jlabel14.getView().setText(StringUtils.formatBigDecimal(lslValue));
        uslAndLslDtoCache.setLslValue(lslValue);
        ((JTextField) (jlabel14.getView())).setHorizontalAlignment(SwingConstants.RIGHT);
        JLabel jlabel15 = new JLabel();
        if (ndcDM.getStandardDto().getCenterValue() != null) {
            jlabel15.setText(StringUtils.formatBigDecimal(String.valueOf(ndcDM.getStandardDto().getCenterValue())));
        } else {
            jlabel15.setText("-");
        }
        jlabel15.setHorizontalAlignment(SwingConstants.RIGHT);
        JLabel jlabel17 = new JLabel();
        if (ndcDM.getPcData().getCaData() != null) {
            jlabel17.setText(StringUtils.formatBigDecimal(formatCAValue(ndcDM.getPcData().getCaData().getValue(), jlabel17)));
            String s17 = ndcDM.getPcData().getCaData().getLevel();
            changeCPWColor(s17, jlabel17);
        } else {
            jlabel17.setText("-");
        }
        JLabel jlabel18 = new JLabel();
        if (ndcDM.getPcData().getCpkData() != null) {
            jlabel18.setText(StringUtils.formatBigDecimal(valueIntoString(ndcDM.getPcData().getCpkData().getValue(), jlabel18)));
            String s18 = ndcDM.getPcData().getCpkData().getLevel();
            changeCPWColor(s18, jlabel18);
        } else {
            jlabel18.setText("-");
        }
        JLabel jlabel19 = new JLabel();
        if (ndcDM.getPcData().getCpData() != null) {
            jlabel19.setText(StringUtils.formatBigDecimal(valueIntoString(ndcDM.getPcData().getCpData().getValue(), jlabel19)));
            String s19 = ndcDM.getPcData().getCpData().getLevel();
            changeCPWColor(s19, jlabel19);
        } else {
            jlabel19.setText("-");
        }
        JLabel jlabel20 = new JLabel();
        if (ndcDM.getPcData().getCplData() != null) {
            jlabel20.setText(StringUtils.formatBigDecimal(valueIntoString(ndcDM.getPcData().getCplData().getValue(), jlabel20)));
            String s20 = ndcDM.getPcData().getCplData().getLevel();
            changeCPWColor(s20, jlabel20);
        } else {
            jlabel20.setText("-");
        }
        JLabel jlabel21 = new JLabel();
        if (ndcDM.getPcData().getCpuData() != null) {
            jlabel21.setText(StringUtils.formatBigDecimal(valueIntoString(ndcDM.getPcData().getCpuData().getValue(), jlabel21)));
            String s21 = ndcDM.getPcData().getCpuData().getLevel();
            changeCPWColor(s21, jlabel21);
        } else {
            jlabel21.setText("-");
        }

        ndcLeftPanel.add(jlabel1, new GBC(1, 1).setFill(GBC.HORIZONTAL));
        ndcLeftPanel.add(jlabel2, new GBC(1, 2).setFill(GBC.HORIZONTAL));
        ndcLeftPanel.add(jlabel3, new GBC(1, 3).setFill(GBC.HORIZONTAL));
        ndcLeftPanel.add(jlabel4, new GBC(1, 4).setFill(GBC.HORIZONTAL));
        ndcLeftPanel.add(jlabel5, new GBC(1, 5).setFill(GBC.HORIZONTAL));
        ndcLeftPanel.add(jlabel6, new GBC(1, 6).setFill(GBC.HORIZONTAL));
        ndcLeftPanel.add(jlabel7, new GBC(1, 7).setFill(GBC.HORIZONTAL));
        ndcLeftPanel.add(jlabel8, new GBC(1, 8).setFill(GBC.HORIZONTAL));
        ndcLeftPanel.add(jlabel9, new GBC(1, 9).setFill(GBC.HORIZONTAL));
        ndcLeftPanel.add(jlabel10, new GBC(1, 10).setFill(GBC.HORIZONTAL));
        ndcLeftPanel.add(jlabel12, new GBC(1, 12).setFill(GBC.HORIZONTAL));
        ndcLeftPanel.add(jlabel13, new GBC(1, 13).setFill(GBC.HORIZONTAL));
        ndcLeftPanel.add(jlabel14, new GBC(1, 14).setFill(GBC.HORIZONTAL));
        ndcLeftPanel.add(jlabel15, new GBC(1, 15).setFill(GBC.HORIZONTAL));
        ndcLeftPanel.add(jlabel17, new GBC(1, 17).setFill(GBC.HORIZONTAL).setInsets(1, 0, 1, 0));
        ndcLeftPanel.add(jlabel18, new GBC(1, 18).setFill(GBC.HORIZONTAL).setInsets(1, 0, 1, 0));
        ndcLeftPanel.add(jlabel19, new GBC(1, 19).setFill(GBC.HORIZONTAL).setInsets(1, 0, 1, 0));
        ndcLeftPanel.add(jlabel20, new GBC(1, 20).setFill(GBC.HORIZONTAL).setInsets(1, 0, 1, 0));
        ndcLeftPanel.add(jlabel21, new GBC(1, 21).setFill(GBC.HORIZONTAL).setInsets(1, 0, 1, 0));
        ndcLeftPanel.add(new JPanel(), new GBC(0, 22).setFill(GBC.BOTH).setWeight(8, 100));
        ndcLeftPanel.add(new JPanel(), new GBC(1, 22).setFill(GBC.BOTH).setWeight(100, 100));

        JPanel ndcRightPanel = new JPanel();
        ndcRightPanel.setLayout(new GridBagLayout());

        NormalDistributionChart chart = new NormalDistributionChart(ndcDM);
        chart.initDigNumFormat(AppConstant.ANALYSIS_SPC_DIGNUM);
        JPanel chartPanel = chart.createChartPanel();
        final Dimension chartPanelSize = new Dimension(100, 100);
        final Dimension ndcRightPanelSize = new Dimension(10, 10);
        chartPanel.setPreferredSize(chartPanelSize);
        ndcRightPanel.setPreferredSize(ndcRightPanelSize);
        ndcRightPanel.add(chartPanel, new GBC(0, 0).setFill(GBC.BOTH).setWeight(100, 100));

        tabSubPanel[0].add(ndcLeftPanel, new GBC(0, 0).setFill(GBC.BOTH).setWeight(3, 100).setInsets(5, 5, 0, 0));
        tabSubPanel[0].add(ndcRightPanel, new GBC(1, 0).setFill(GBC.BOTH).setWeight(100, 100));
        tabSubPanel[0].updateUI();

        ndChartsEventTip.setText("The NDChart and ScatterChart groups are invalid ");
        ndChartsEventTip.setForeground(Color.red);
        ndChartsEventTip.setVisible(false);
        if (spcConfigDto.getSpcNdGroup() != null) {
            if (dataCount < spcConfigDto.getSpcNdGroup()) {
                ndChartsEventTip.setVisible(true);
            }
        }
        if (groupsDtoCache.getGroups() != null) {
            if (dataCount < Integer.parseInt(groupsDtoCache.getGroups())) {
                ndChartsEventTip.setVisible(true);
            }
        }
    }

    private void drawScatterChart() {
        if (tabSubPanel[1] != null) {
            tabSubPanel[1].removeAll();
        } else {
            tabSubPanel[1] = new JPanel();
        }
        if (chartDataModal.getData(ChartDataModal.CHART_SC) == null) {
            return;
        }
        ScatterDto scatterDto = (ScatterDto) chartDataModal.getData(ChartDataModal.CHART_SC);
        tabSubPanel[1].setLayout(new GridBagLayout());
        JPanel scatterLeftPanel = new JPanel();
        scatterLeftPanel.setLayout(new GridBagLayout());
        String[] labelNames = new String[]{
                "Statistical", "Samples", "AVG", "Max", "Min", "Range", "StDev", "LCL", "UCL", "Kurtosis", "Skewness",
                "AppConstant", "Groups", "USL", "LSL", "Center",
                "Capability Index", "CA(%)", "CPK", "CP", "CPL", "CPU"};
        int i;
        for (i = 0; i < labelNames.length; i++) {
            JLabel label = new JLabel();
            label.setText(labelNames[i]);
            scatterLeftPanel.add(label, new GBC(0, i).setFill(GBC.HORIZONTAL));
            if (i == 0 || i == 11 || i == 16) {
                label.setFont(label.getFont().deriveFont(Font.BOLD));
                scatterLeftPanel.add(label, new GBC(0, i, 2, 1).setFill(GBC.HORIZONTAL));
            }
        }
        boolean statistics = true;
        if (scatterDto.getStatisticsDto() == null) {
            statistics = false;
        }
        JLabel jlabel1 = new JLabel();
        dataCount = scatterDto.getStatisticsDto().getDataCount();
        jlabel1.setText(statistics ? StringUtils.formatBigDecimal((int) ((double) dataCount) + "") : "-");
        jlabel1.setHorizontalAlignment(SwingConstants.RIGHT);
        JLabel jlabel2 = new JLabel();
        Double avgValue = scatterDto.getStatisticsDto().getAvgValue();
        jlabel2.setText(statistics ? StringUtils.formatBigDecimal(valueIntoString(avgValue, jlabel2)) : "-");
        JLabel jlabel3 = new JLabel();
        Double maxValue = scatterDto.getStatisticsDto().getMaxValue();
        jlabel3.setText(statistics ? StringUtils.formatBigDecimal(valueIntoString(maxValue, jlabel3)) : "-");
        JLabel jlabel4 = new JLabel();
        Double minValue = scatterDto.getStatisticsDto().getMinValue();
        jlabel4.setText(statistics ? StringUtils.formatBigDecimal(valueIntoString(minValue, jlabel4)) : "-");
        JLabel jlabel5 = new JLabel();
        Double rangeValue = scatterDto.getStatisticsDto().getRangeValue();
        jlabel5.setText(statistics ? StringUtils.formatBigDecimal(valueIntoString(rangeValue, jlabel5)) : "-");
        JLabel jlabel6 = new JLabel();
        Double stdValue = scatterDto.getStatisticsDto().getStdValue();
        jlabel6.setText(statistics ? StringUtils.formatBigDecimal(valueIntoString(stdValue, jlabel6)) : "-");
        JLabel jlabel7 = new JLabel();
        Double lclValue = scatterDto.getStatisticsDto().getLclValue();
        jlabel7.setText(statistics ? StringUtils.formatBigDecimal(valueIntoString(lclValue, jlabel7)) : "-");
        JLabel jlabel8 = new JLabel();
        Double uclValue = scatterDto.getStatisticsDto().getUclValue();
        jlabel8.setText(statistics ? StringUtils.formatBigDecimal(valueIntoString(uclValue, jlabel8)) : "-");
        JLabel jlabel9 = new JLabel();
        Double kurtosisValue = scatterDto.getStatisticsDto().getKurtosisValue();
        jlabel9.setText(statistics ? StringUtils.formatBigDecimal(valueIntoString(kurtosisValue, jlabel9)) : "-");
        JLabel jlabel10 = new JLabel();
        Double skewnessValue = scatterDto.getStatisticsDto().getSkewnessValue();
        jlabel10.setText(statistics ? StringUtils.formatBigDecimal(valueIntoString(skewnessValue, jlabel10)) : "-");

        boolean statistics1 = true;
        if (scatterDto.getStandardDto() == null) {
            statistics1 = false;
        }
        jlabel12 = GuiComponentFactory.createTextField(bg, groupsDto, groupsDto.PROPERTYNAME_GROUPS);
        int groups = scatterDto.getStandardDto().getGroupValue();
        jlabel12.getView().setText(statistics1 ? StringUtils.formatBigDecimal(groups + "") : "-");
        groupsDtoCache.setGroups(String.valueOf(groups));
        ((JTextField) (jlabel12.getView())).setHorizontalAlignment(SwingConstants.RIGHT);

        jlabel13 = GuiComponentFactory.createTextField(bg, uslAndLslDto, uslAndLslDto.PROPERTYNAME_USL);
        Double tempUsl = scatterDto.getStandardDto().getUslValue();
        String uslValue = null;
        if (tempUsl != null) {
            uslValue = tempUsl + "";
        } else {
            uslValue = "";
        }
        jlabel13.getView().setText(StringUtils.formatBigDecimal(uslValue));
        uslAndLslDtoCache.setUslValue(uslValue);
        ((JTextField) (jlabel13.getView())).setHorizontalAlignment(SwingConstants.RIGHT);
        jlabel14 = GuiComponentFactory.createTextField(bg, uslAndLslDto, uslAndLslDto.PROPERTYNAME_LSL);
        Double tempLsl = scatterDto.getStandardDto().getLslValue();
        String lslValue = null;
        if (tempLsl != null) {
            lslValue = tempLsl + "";
        } else {
            lslValue = "";
        }
        jlabel14.getView().setText(StringUtils.formatBigDecimal(lslValue));
        uslAndLslDtoCache.setLslValue(lslValue);
        ((JTextField) (jlabel14.getView())).setHorizontalAlignment(SwingConstants.RIGHT);
        JLabel jlabel15 = new JLabel();
        if (scatterDto.getStandardDto().getCenterValue() != null) {
            jlabel15.setText(StringUtils.formatBigDecimal(String.valueOf(scatterDto.getStandardDto().getCenterValue())));
        } else {
            jlabel15.setText("-");
        }
        jlabel15.setHorizontalAlignment(SwingConstants.RIGHT);
        JLabel jlabel17 = new JLabel();
        if (scatterDto.getPcData().getCaData() != null) {
            jlabel17.setText(StringUtils.formatBigDecimal(formatCAValue(scatterDto.getPcData().getCaData().getValue(), jlabel17)));
            String s17 = scatterDto.getPcData().getCaData().getLevel();
            changeCPWColor(s17, jlabel17);
        } else {
            jlabel17.setText("-");
        }
        JLabel jlabel18 = new JLabel();
        if (scatterDto.getPcData().getCpkData() != null) {
            jlabel18.setText(StringUtils.formatBigDecimal(valueIntoString(scatterDto.getPcData().getCpkData().getValue(), jlabel18)));
            String s18 = scatterDto.getPcData().getCpkData().getLevel();
            changeCPWColor(s18, jlabel18);
        } else {
            jlabel18.setText("-");
        }
        JLabel jlabel19 = new JLabel();
        if (scatterDto.getPcData().getCpData() != null) {
            jlabel19.setText(StringUtils.formatBigDecimal(valueIntoString(scatterDto.getPcData().getCpData().getValue(), jlabel19)));
            String s19 = scatterDto.getPcData().getCpData().getLevel();
            changeCPWColor(s19, jlabel19);
        } else {
            jlabel19.setText("-");
        }
        JLabel jlabel20 = new JLabel();
        if (scatterDto.getPcData().getCplData() != null) {
            jlabel20.setText(StringUtils.formatBigDecimal(valueIntoString(scatterDto.getPcData().getCplData().getValue(), jlabel20)));
            String s20 = scatterDto.getPcData().getCplData().getLevel();
            changeCPWColor(s20, jlabel20);
        } else {
            jlabel20.setText("-");
        }
        JLabel jlabel21 = new JLabel();
        if (scatterDto.getPcData().getCpuData() != null) {
            jlabel21.setText(StringUtils.formatBigDecimal(valueIntoString(scatterDto.getPcData().getCpuData().getValue(), jlabel21)));
            String s21 = scatterDto.getPcData().getCpuData().getLevel();
            changeCPWColor(s21, jlabel21);
        } else {
            jlabel21.setText("-");
        }
        scatterLeftPanel.add(jlabel1, new GBC(1, 1).setFill(GBC.HORIZONTAL));
        scatterLeftPanel.add(jlabel2, new GBC(1, 2).setFill(GBC.HORIZONTAL));
        scatterLeftPanel.add(jlabel3, new GBC(1, 3).setFill(GBC.HORIZONTAL));
        scatterLeftPanel.add(jlabel4, new GBC(1, 4).setFill(GBC.HORIZONTAL));
        scatterLeftPanel.add(jlabel5, new GBC(1, 5).setFill(GBC.HORIZONTAL));
        scatterLeftPanel.add(jlabel6, new GBC(1, 6).setFill(GBC.HORIZONTAL));
        scatterLeftPanel.add(jlabel7, new GBC(1, 7).setFill(GBC.HORIZONTAL));
        scatterLeftPanel.add(jlabel8, new GBC(1, 8).setFill(GBC.HORIZONTAL));
        scatterLeftPanel.add(jlabel9, new GBC(1, 9).setFill(GBC.HORIZONTAL));
        scatterLeftPanel.add(jlabel10, new GBC(1, 10).setFill(GBC.HORIZONTAL));
        scatterLeftPanel.add(jlabel12, new GBC(1, 12).setFill(GBC.HORIZONTAL));
        scatterLeftPanel.add(jlabel13, new GBC(1, 13).setFill(GBC.HORIZONTAL));
        scatterLeftPanel.add(jlabel14, new GBC(1, 14).setFill(GBC.HORIZONTAL));
        scatterLeftPanel.add(jlabel15, new GBC(1, 15).setFill(GBC.HORIZONTAL));
        scatterLeftPanel.add(jlabel17, new GBC(1, 17).setFill(GBC.HORIZONTAL).setInsets(1, 0, 1, 0));
        scatterLeftPanel.add(jlabel18, new GBC(1, 18).setFill(GBC.HORIZONTAL).setInsets(1, 0, 1, 0));
        scatterLeftPanel.add(jlabel19, new GBC(1, 19).setFill(GBC.HORIZONTAL).setInsets(1, 0, 1, 0));
        scatterLeftPanel.add(jlabel20, new GBC(1, 20).setFill(GBC.HORIZONTAL).setInsets(1, 0, 1, 0));
        scatterLeftPanel.add(jlabel21, new GBC(1, 21).setFill(GBC.HORIZONTAL).setInsets(1, 0, 1, 0));
        scatterLeftPanel.add(new JPanel(), new GBC(0, 22).setFill(GBC.BOTH).setWeight(8, 100));
        scatterLeftPanel.add(new JPanel(), new GBC(1, 22).setFill(GBC.BOTH).setWeight(100, 100));

        JPanel scatterRightPanel = new JPanel();
        scatterRightPanel.setLayout(new GridBagLayout());
        ScatterChart chart = new ScatterChart(scatterDto);
        chart.initDigNumFormat(AppConstant.ANALYSIS_SPC_DIGNUM);
        scatterRightPanel.add(chart.createChartPanel(), new GBC(0, 0).setFill(GBC.BOTH).setWeight(100, 100));
        tabSubPanel[1].add(scatterLeftPanel, new GBC(0, 0).setFill(GBC.BOTH).setWeight(3, 100).setInsets(5, 5, 0, 0));
        tabSubPanel[1].add(scatterRightPanel, new GBC(1, 0).setFill(GBC.BOTH).setWeight(100, 100));
        tabSubPanel[1].updateUI();
        ndChartsEventTip.setText("The NDChart and ScatterChart groups are invalid ");
        ndChartsEventTip.setForeground(Color.red);
        ndChartsEventTip.setVisible(false);
        if (spcConfigDto.getSpcNdGroup() != null) {
            if (dataCount < spcConfigDto.getSpcNdGroup()) {
                ndChartsEventTip.setVisible(true);
            }
        }
        if (groupsDtoCache.getGroups() != null) {
            if (dataCount < Integer.parseInt(groupsDtoCache.getGroups())) {
                ndChartsEventTip.setVisible(true);
            }
        }
    }

    private void drawControlChartPanel(int index) {
        String chartName = chartTabPanel.getTitleAt(index);
        if (tabSubPanel[index] != null) {
            tabSubPanel[index].removeAll();
        } else {
            tabSubPanel[index] = new JPanel();
        }
        ControlDataDto controlDataDto = null;
        if (index == 2) {
            controlDataDto = (ControlDataDto) chartDataModal.getData(ChartDataModal.CHART_RUN);
        } else if (index == 3) {
            controlDataDto = (ControlDataDto) chartDataModal.getData(ChartDataModal.CHART_XBAR);
        } else if (index == 4) {
            controlDataDto = (ControlDataDto) chartDataModal.getData(ChartDataModal.CHART_SD);
        } else if (index == 5) {
            controlDataDto = (ControlDataDto) chartDataModal.getData(ChartDataModal.CHART_R);
        } else if (index == 6) {
            controlDataDto = (ControlDataDto) chartDataModal.getData(ChartDataModal.CHART_MR);
        }
        tabSubPanel[index].setLayout(new GridBagLayout());
        JPanel rulePanel = new JPanel();
        rulePanel.setLayout(new GridBagLayout());
        if (controlDataDto == null) {
            tabSubPanel[index].removeAll();
            tabSubPanel[index].updateUI();
        } else {
            List<RuleResultDto> ruleResults = controlDataDto.getRuleResultList();
            if (ruleResults != null) {
                int i = 0;
                for (; i < ruleResults.size(); i++) {
                    RuleResultDto ruleResult = ruleResults.get(i);
                    if (Strings.isNotEmpty(ruleResult.getRuleName())) {
                        RoundRectLabel label = new RoundRectLabel(ruleResult.getRuleName(), 2, 4);
                        if (ruleResult.isOverRule()) {
                            label.setOpaque(true);
                            label.setBackground(Colur.RED);
                            label.setForeground(Colur.WHITE);
                            if (ruleResult.getRuleName() == "R1") {
                                label.setText(String.valueOf("R1[" + ruleResult.getPos() + "]"));
                            }
                        }

                        List<SysSpcCcwDto> sysSpcCcwDtos = sysSpcDto.getSysSpcCcwDtos();
                        switch (ruleResult.getRuleName()) {
                            case "R1":
                                label.setToolTipText("[" + sysSpcCcwDtos.get(0).getValue1() + "] point falls outside the [" + sysSpcCcwDtos.get(0).getValue3() + "]σ limit from the centerline");
                                break;
                            case "R2":
                                label.setToolTipText("[" + sysSpcCcwDtos.get(1).getValue1() + "] (or more) consecutive points fall on the same side of the centerline");
                                break;
                            case "R3":
                                label.setToolTipText("[" + sysSpcCcwDtos.get(2).getValue1() + "] (or more) points in a row are continually increasing or decreasing");
                                break;
                            case "R4":
                                label.setToolTipText("[" + sysSpcCcwDtos.get(3).getValue1() + "] points in a row alternate in direction, increasing then decreasing");
                                break;
                            case "R5":
                                label.setToolTipText("[" + sysSpcCcwDtos.get(4).getValue2() + "] out of [" + sysSpcCcwDtos.get(4).getValue1() + "] consecutive points fall beyond the ["
                                        + sysSpcCcwDtos.get(4).getValue3() + "]σ limit, on the same side of the centerline");
                                break;
                            case "R6":
                                label.setToolTipText("[" + sysSpcCcwDtos.get(5).getValue2() + "] out of [" + sysSpcCcwDtos.get(5).getValue1() + "] consecutive points fall beyond the ["
                                        + sysSpcCcwDtos.get(5).getValue3() + "]σ limit, on the same side of the centerline");
                                break;
                            case "R7":
                                label.setToolTipText("[" + sysSpcCcwDtos.get(6).getValue1() + "] points in a row are all within the ["
                                        + sysSpcCcwDtos.get(6).getValue3() + "]σ limit, on either side of the centerline");
                                break;
                            case "R8":
                                label.setToolTipText("[" + sysSpcCcwDtos.get(7).getValue1() + "] points in a row exist with none within the ["
                                        + sysSpcCcwDtos.get(7).getValue3() + "]σ limit, and the points a in both directions from the centerline");
                                break;
                            default:
                                break;
                        }
                        rulePanel.add(label, new GBC(i, 0).setFill(GBC.HORIZONTAL).setWeight(1, 1).setInsets(5));
                    }
                }
                rulePanel.add(new JLabel(), new GBC(i, 0).setFill(GBC.HORIZONTAL).setWeight(100, 1));

            }

            JPanel chartPanel = new JPanel();
            chartPanel.setLayout(new GridBagLayout());
            ChartDto chartDto = new ChartDto();
            chartDto.setName(chartName);
            ControlChart chart = new ControlChart(controlDataDto, chartDto);
            chart.initDigNumFormat(AppConstant.ANALYSIS_SPC_DIGNUM);
            chartPanel.add(chart.createChartPanel(), new GBC(0, 0).setFill(GBC.BOTH).setWeight(100, 100));
            tabSubPanel[index].add(rulePanel, new GBC(0, 0).setFill(GBC.BOTH).setWeight(10, 5));

            if (index == 2 || index == 6) {
                ControlChartDynamicLineChart controlChart = new ControlChartDynamicLineChart(controlDataDto, chartDto);
                controlChart.setDigitNum(AppConstant.ANALYSIS_SPC_DIGNUM);
                controlChart.initDigNumFormat(AppConstant.ANALYSIS_SPC_DIGNUM);
                tabSubPanel[index].add(controlChart.getPanel(), new GBC(0, 1).setFill(GBC.BOTH).setWeight(100, 100));
                controlChartDynamicLineChartMap.put(chartDto.getName(), controlChart);
            } else {
                ControlChart controlChart = new ControlChart(controlDataDto, chartDto);
                controlChart.initDigNumFormat(AppConstant.ANALYSIS_SPC_DIGNUM);
                tabSubPanel[index].add(controlChart.createChartPanel(), new GBC(0, 1).setFill(GBC.BOTH).setWeight(100, 100));
            }
        }

        controlChartsEventTip.setText("The controlChart group is invalid ");
        controlChartsEventTip.setForeground(Color.red);
        controlChartsEventTip.setVisible(false);
        if (spcConfigDto.getSpcCcGroup() != null) {
            double controlDataCount = ((ControlDataDto) chartDataModal.getData(ChartDataModal.CHART_RUN)).getDataCount();
            if (controlDataCount < spcConfigDto.getSpcCcGroup()) {
                controlChartsEventTip.setVisible(true);
            }
        }
    }

    private void changeCPWColor(String code, JLabel label) {
        switch (code) {
            case "NORMAL":
                label.setForeground(Colur.BLACK);
                break;
            case "EXCELLENT":
                label.setBackground(Colur.GREEN);
                label.setForeground(Colur.BLACK);
                label.setOpaque(true);
                break;
            case "GOOD":
                label.setBackground(Colur.BLUE);
                label.setForeground(Colur.BLACK);
                label.setOpaque(true);
                break;
            case "ACCEPTABLE":
                label.setBackground(Colur.YELLOW);
                label.setForeground(Colur.BLACK);
                label.setOpaque(true);
                break;
            case "ABOVE_RECTIFICATION":
                label.setBackground(Colur.ORANGE);
                label.setForeground(Colur.BLACK);
                label.setOpaque(true);
                break;
            case "RECTIFICATION":
                label.setBackground(Colur.RED);
                label.setForeground(Colur.BLACK);
                label.setOpaque(true);
                break;
            default:
                label.setForeground(Colur.BLACK);
                break;
        }
    }

    private void setBtnEnable() {
        if (fileFlag && analyseFlag) {
            searchButton.setEnabled(true);
            EventBusUtils.post(new ExportBtnEnabledEvent(UIConstant.MODULE_SPC, true));
        } else {
            searchButton.setEnabled(false);
            EventBusUtils.post(new ExportBtnEnabledEvent(UIConstant.MODULE_SPC, false));
        }

        if (fileFlag && searchFlag && searchKeyFlag && testItemFlag) {
            spcChartRefreshButton.setEnabled(true);
        } else {
            spcChartRefreshButton.setEnabled(false);
        }
    }

    private int[] getTableViewData() {
        int[] items = new int[testDataTable.getRowCount()];
        for (int i = 0; i < testDataTable.getRowCount(); i++) {
            items[i] = testDataTable.convertRowIndexToModel(i);
        }
        return items;
    }

    private String valueIntoString(Double value, JLabel jLabel) {
        int digit = Integer.parseInt(sysSpcDto.getDigit());
        String newValue = null;
        if (digit == 0) {
            newValue = String.format("%." + 0 + "f", value);
        } else {
            newValue = String.format("%." + digit + "f", value);
        }
        jLabel.setHorizontalAlignment(SwingConstants.RIGHT);
        return newValue;
    }

    private String formatCAValue(Double value, JLabel jLabel) {
        int digit = Integer.parseInt(sysSpcDto.getDigit());
        String newValue = null;
        if (digit <= 2) {
            newValue = String.format("%." + 0 + "f", value);
        } else if (digit > 2) {
            newValue = String.format("%." + (digit - 2) + "f", value);
        }
        jLabel.setHorizontalAlignment(SwingConstants.RIGHT);
        return newValue;
    }

    private AnalysisFilePanel analysisFilePanel;
    private AnalysisItemPanel analysisItemPanel;
    private AnalysisSearchPanel analysisSearchPanel;
    private JButton searchButton;
    private JPanel rightPanel;

    private Map<String, NDStandardDto> itemNameAndValueCache;

    private Double dataCount;

    private JTabbedPane chartTabPanel;
    private JPanel testDataPanel;
    private JPanel[] tabSubPanel;
    private JTextFieldEx testDataFilter;
    private ButtonGroup testDataBg;
    private JRadioButton testDataAllButton;
    private JRadioButton testDataSelectedButton;
    private JRadioButton testDataUnSelectedButton;
    private JButton testDataResetButton;
    private JTable testDataTable;
    private TableRowSorter testDataTableSorter;

    private boolean fileFlag = false;
    private boolean analyseFlag = false;
    private boolean testItemFlag = false;
    private boolean searchKeyFlag = false;
    private boolean searchFlag = false;

    private JButton spcChartRefreshButton;
    private JLabel ndChartsEventTip;
    private JLabel controlChartsEventTip;
    private JXLayer<JTextComponent> jlabel12;
    private JXLayer<JTextComponent> jlabel13;
    private JXLayer<JTextComponent> jlabel14;
    private BindingGroup bg;
    private SpcExportAllDialog spcExportAllDialog;
    private SpcExportMultipleItemDialog spcExportMultipleItemDialog;
    private Map<String, ControlChartDynamicLineChart> controlChartDynamicLineChartMap;
    private SpcConfigDto spcConfigDto;
    private SysSpcDto sysSpcDto;
}
